package LinkList;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: LinkList
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-11-02  08:52
 * @Description: TODO
 * @Version: 1.0
 */
public class 二叉树展开为链表114 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode curr = root;
        // 判断当前节点是否为空
        while (curr != null) {
            // 如果当前节点没有左孩子，直接跳过，否者就是找到这个左子树中最右边节点
            if (curr.left != null) {
                // 左子树的头部
                TreeNode next = curr.left;
                TreeNode predecessor = next;
                // 找到左子树的最右边的节点
                while (predecessor.right != null) {
                    predecessor = predecessor.right;
                }
                // 最右边的节点设置为当前节点的右指针
                predecessor.right = curr.right;
                // 同时设置当前为左指针为null
                curr.left = null;
                // 将当前节点左边边设置右边（右指针指向左边）
                curr.right = next;
            }
            // 每一次都是使得当前都下一个节点等于这个节点
            curr = curr.right;
        }
    }

    public void flatten2(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left != null) {
                TreeNode next = curr.left;
                TreeNode node = next;
                while (node.right != null) {
                    node = node.right;
                }
                node.right = curr.right;
                curr.left = null;
                curr.right = next;
            } else {
                curr = curr.right;
            }
        }
    }
}
